<template>
  <div class="container">
    <!-- 搜索框 -->
    <el-input
      v-model="searchQuery"
      placeholder="搜索.."
      clearable
      @keyup.enter="handleSearch"
      class="search-input"
    >
      <template #prefix>
        <el-icon><Search /></el-icon>
      </template>
      <template #append>
        <el-button @click="handleSearch">搜索</el-button>
      </template>
    </el-input>

    <!-- 展示搜索结果 -->
    <div v-if="hasResults" class="search-results">
      <p>搜索结果：</p>
      <el-row :gutter="16">
        <el-col 
          v-for="(item, index) in paginatedResults" 
          :key="index" 
          :span="getSpanValue(paginatedResults.length)"
        >
          <el-card class="file-card" shadow="hover">
            <div class="card-header" @click="handlePreview(item)">
              <svg-icon 
                width="45px" 
                height="45px" 
                :icon-name="getFileTypeIcon(item.fileType).iconName" 
                :icon-color="getFileTypeIcon(item.fileType).iconColor" 
              />
              <span class="card-title" :title="item.name">{{ item.name }}</span>
            </div>
            <div slot="footer" class="card-footer">
              <div class="actions">
                <el-button type="text" icon="el-icon-download" @click.stop="handleDownload(item)">下载</el-button>
                <el-button 
                  type="text" 
                  icon="el-icon-view"              
                  @click.stop="handlePreview(item)"
                >预览</el-button>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
      <!-- 分页控件 -->
      <el-pagination
        layout="prev, pager, next"
        :total="totalResults"
        :page-size="pageSize"
        :current-page.sync="currentPage"
        @current-change="handlePageChange"
        class="pagination"
      />
    </div>
    <div v-else>
      <el-empty description="未找到匹配的文件" />
    </div>
    
    <!-- 预览对话框        :height="`${previewHeight}px`"-->
    <el-dialog
      v-model="previewVisible" 
      :width="`${previewWidth}px`"
      fullscreen
      top="5vh"
      class="preview-dialog"
      @close="closePreview"
    >
      <!-- 使用 FileView 组件进行预览 -->
      <file-preview  :file="previewFile" :file-type="previewType"></file-preview>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { attachmentDownloadById, attachmentPreviewById, attachmentSearch } from '@/api/repo/attachment';
import FilePreview from '@/components/FilePreview/index.vue'; // 假设 FileView 组件在同一目录下
import download from '@/utils/down/download';
import { Search } from '@element-plus/icons-vue';
import { ElButton, ElCard, ElCol, ElDialog, ElImage, ElInput, ElMessage, ElPagination, ElRow } from 'element-plus';
import { computed, defineComponent, ref } from 'vue';


// 文件类型定义
const fileTypes = [
  { value: 'doc', label: 'Word (.doc, .docx)', iconName: 'word', iconColor: '#007bff' },
  { value: 'docx', label: 'Word (.doc, .docx)', iconName: 'word', iconColor: '#007bff' },
  { value: 'xls', label: 'Excel (.xls, .xlsx, .csv)', iconName: 'excel', iconColor: '#28a745' },
  { value: 'xlsx', label: 'Excel (.xls, .xlsx, .csv)', iconName: 'excel', iconColor: '#28a745' },
  { value: 'pdf', label: 'PDF (.pdf)', iconName: 'pdf', iconColor: '#dc3545' },
  { value: 'ppt', label: 'PPT (.ppt)', iconName: 'ppt', iconColor: '#dc3545' },
  { value: 'pptx', label: 'PPT (.ppt)', iconName: 'ppt', iconColor: '#dc3545' },
  { value: 'dwg', label: 'AutoCAD (.dwg)', iconName: 'dwg', iconColor: '#6c757d' },
  { value: 'image', label: '图片 (.jpg, .png, .gif)', iconName: 'pic', iconColor: '#ffc107' },
  { value: 'txt', label: '文本 (.txt)', iconName: 'txt', iconColor: '#17a2b8' }, 
  { value: 'ofd', label: 'OFD (.ofd)', iconName: 'ofd', iconColor: '#f39c12' }, 
  { value: 'mp4', label: '视频 (.mp4, .avi, .mkv)', iconName: 'video', iconColor: '#e65100' }, 
  { value: 'avi', label: '视频 (.mp4, .avi, .mkv)', iconName: 'video', iconColor: '#e65100' }, 
];

export default defineComponent({
  name: 'SearchView',
  components: {
    ElInput,
    ElImage,
    ElCard,
    ElRow,
    ElCol,
    ElButton,
    ElPagination,
    ElDialog,
    Search,
    FilePreview // 引入 FileView 组件
  },
  setup() {
    const searchQuery = ref('');
    const searchResults = ref<any[]>([]);
    const currentPage = ref(1);
    const pageSize = ref(8); // 每页显示的项目数量
    const totalResults = ref(0);

    const previewVisible = ref(false);
    const previewType = ref<string>('');
    const previewFile = ref<Blob | null>(null);
    const previewWidth = ref<number>(800);
    const previewHeight = ref<number>(900);

    const hasResults = computed(() => paginatedResults.value.length > 0);

    const getIconByType = (type: string): { iconName: string; iconColor: string } => {
      const fileType = fileTypes.find(ft => ft.value === type.toLowerCase()) || fileTypes.find(ft => ft.value === 'txt');
      return {
        iconName: fileType?.iconName || 'other',
        iconColor: fileType?.iconColor || '#6c757d'
      };
    };

    function getSpanValue(length: number): number {
      if (length >= 4) return 6;
      if (length === 3) return 8;
      if (length === 2) return 12;
      return 24; // 如果只有一个项目
    }

    async function handleSearch() {
      if (!searchQuery.value.trim()){
        ElMessage.warning('请输入搜索关键词');
        searchResults.value = [];
        totalResults.value = 0;
        return;
      } 

      searchResultsFun(1);
    }

    async function searchResultsFun(pageNum: number) {
      try {
        const response = await attachmentSearch({
          keyword: searchQuery.value,
          // pageNum: currentPage.value,
          pageNum: pageNum,
          pageSize: pageSize.value
        });
        searchResults.value = response.content || [];
        totalResults.value = response.totalElements || 0;
      } catch (error) {
        console.error('搜索过程中发生错误:', error);
      }
    }

    // const paginatedResults = computed(() => {
    //   const start = (currentPage.value - 1) * pageSize.value;
    //   const end = start + pageSize.value;
    //   return searchResults.value.slice(start, end);
    // });
    const paginatedResults = computed(() => {
      // 不需要手动分片，因为后端应该已经根据 pageNum 和 pageSize 返回了分页后的结果
      return searchResults.value;
    });

    function handlePageChange(page: number) {
      currentPage.value = page;
      searchResultsFun(currentPage.value);
    }

    async function handlePreview(item: any) {
      previewType.value = item.fileType;
      try {
        const response = await attachmentPreviewById({ attachmentId: item.id });
        if (response instanceof Blob) {
          previewFile.value = response;
          previewVisible.value = true;
        } else {
          console.error('下载响应不是预期的 Blob 类型');
        }
      } catch (error) {
        console.error('获取文件预览失败:', error);
      }
    }

    function closePreview() {
      previewVisible.value = false;
      previewFile.value = null;
    }

    async function handleDownload(item: any) {
      try {
        const response = await attachmentDownloadById({ attachmentId: item.id });
        if (response instanceof Blob) {
          download.default(response, item.name);
        } else {
          console.error('下载响应不是预期的 Blob 类型');
        }
      } catch (error) {
        ElMessage.error('下载文件失败');
      }
    }

    const getFileTypeIcon = (type: string) => getIconByType(type);
    const isDirectory = (type: string) => type.toLowerCase() === 'dir';

    return {
      getSpanValue,
      searchQuery,
      handleSearch,
      searchResults,
      currentPage,
      pageSize,
      totalResults,
      paginatedResults,
      handlePageChange,
      handlePreview,
      previewVisible,
      previewType,
      previewFile,
      previewWidth,
      previewHeight,
      closePreview,
      handleDownload,
      getFileTypeIcon,
      isDirectory,
      hasResults
    };
  }
});
</script>
<style scoped>
/* 设置预览对话框的最大高度 */
.preview-dialog {
  max-height: calc(100vh - 100px); /* 假设顶部导航栏高度为100px */
}

/* 确保对话框内的内容是可滚动的 */
.dialog-content {
  max-height: calc(100vh - 200px); /* 减去对话框标题、底部间距等 */
  overflow-y: auto;
}

.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  background-color: var(--el-bg-color-base);
}

.search-input {
  margin-bottom: 15px;
}

.search-results {
  margin-left: 20px;
}

.file-card {
  margin-bottom: 15px;
  text-align: center;
}

.card-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-footer span {
  max-width: 60%;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  flex-shrink: 1;
}

.card-title {
  display: inline-block;
  max-width: 100%; /* 或者根据需要设置一个具体的宽度 */
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.actions {
  display: flex;
  gap: 8px;
  flex-shrink: 0;
}

.pagination {
  margin-top: 15px;
}

.card-header{
  display: flex;
  flex-direction: column;
  align-items: center;
}


</style>
